--[[
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


    ###Parsing bit is Based on swf.py from Jsunpack which is GPLv2 so we use that as well
    https://code.google.com/p/jsunpack-n/source/browse/trunk/swf.py

    ####Example prefilter rules. Worked with Contagio .doc samples but had to set libhtp to insane settings below. Ideally we should be able to at least set flow int's from lua so we can create streaming parsers.

     response-body-minimal-inspect-size: 65kb
     response-body-inspect-window: 65kb


    #New rules
    alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"ET WEB_CLIENT Adobe Flash Vuln (CVE-2012-1535 Uncompressed) "; flow:from_server,established; file_data; content:"FWS"; depth:3; luajit:CVE-2012-1535.lua; content:"kern"; fast_pattern:only; classtype:trojan-activity; sid:7016688; rev:4;)
    alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"ET WEB_CLIENT Adobe Flash Vuln (CVE-2012-1535 Compressed)"; flow:from_server,established; file_data; content:"CWS"; depth:3; luajit:CVE-2012-1535.lua; classtype:trojan-activity; sid:7016687; rev:4;)
    alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"ET WEB_CLIENT Adobe Flash Vuln (CVE-2012-1535 Uncompressed) "; flow:from_server,established; file_data; flowbits:isset,OLE.CompoundFile; content:"kern"; fast_pattern:only;  content:"FWS"; luajit:CVE-2012-1535.lua; classtype:trojan-activity; sid:6688; rev:4;)
    alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"ET WEB_CLIENT Adobe Flash Vuln (CVE-2012-1535 Compressed)"; flow:from_server,established; file_data; flowbits:isset,OLE.CompoundFile; content:"CWS"; luajit:CVE-2012-1535.lua; classtype:trojan-activity; sid:6687; rev:4;)

    #Existing rules
    alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"ET WEB_CLIENT Microsoft OLE Compound File Magic Bytes Flowbit Set"; flow:to_client,established; content:"|d0 cf 11 e0 a1 b1 1a e1|"; content:!".msi"; flowbits:set,OLE.CompoundFile; flowbits:noalert; classtype:protocol-command-decode; sid:2012520; rev:6;)

    ###Requirements
    
    #struct module
    sudo luarocks install struct

    #lua-zlib
    https://github.com/brimworks/lua-zlib
   
    ###Technical Description of the Vuln
    http://www.exploit-db.com/wp-content/themes/exploit/docs/21928.pdf
--]]

-- CVE-2012-1535 --
local lz = require 'zlib'
local s = require 'struct'
local bit = require("bit")

function init (args)
    local needs = {}
    needs["http.response_body"] = tostring(true)
    return needs
end

function match(args)
    local t = tostring(args["http.response_body"])

    -- CWS and FWS are both 3 bytes long
    -- Method should work for Flash inside of OLE etc.
    local o = args["offset"]
    t = string.sub(t,o - 3) 
    local tlen = string.len(t)

    --Parse the SWF Header
    local sig = string.sub(t,1, 3)
    local ver = string.byte(t,4)
    local len = s.unpack("<I4",string.sub(t,5,8))

    --subtract sig,ver,len
    local parsed_len = (len - 8)

    -- store uncompressed length
    local uncompressed_len = 0

    if sig  == "CWS" then 
        stream = lz.inflate()
        t, eof, bytes_in, uncompressed_len = stream(string.sub(t,9))
        if string.find(t,"kern",9,true) == nil then
            return 0
        end
    elseif sig ~= "FWS" then
        print("Not a SWF file bailing" .. sig)
        return 0
    end

    local offset = 9 
    --get number of bits in the rect
    local rectbits = bit.rshift(string.byte(t,9),3)

    if ((rectbits * 4) % 8) == 0 then
        more = rectbits * 4 / 8
    else
        more = math.floor(rectbits * 4 / 8) + 1
    end

    offset = offset + more + 1
    offset = offset + 4 

    --iterate over the tags---
    while offset + 1 < len do
        b = string.byte(t,offset)
        a = string.byte(t,offset + 1)

        -- Out of bytes
        if a == nil or b == nil then 
           --print("out of bytes " .. a,b)
           return 0
        end

        -- get tag bits --
        offset = offset + 2
        tagtype = bit.band(((bit.lshift(a,2)) + (bit.rshift(b,6))),0x03ff)
        shortlen = bit.band(b,0x3f)

        -- is this a long tag format?
        if shortlen == 0x3f then
            shortlen = s.unpack("<I4",string.sub(t,offset,offset+4))
            offset = offset + 4
        end

        if tagtype == 91 then
            ttfoffset = offset + 3
            -- Find the end of the font name
            ttfoffset = string.find(t,'\000',ttfoffset,true) + 1
            --print(ttfoffset)            
            ttf = string.sub(t,ttfoffset, ttfoffset + shortlen)
            ktag = string.find(ttf,'kern',12,true)
            if ktag ~= nil then
                -- Inside TTF we are big endian
                ktoffset = s.unpack(">I4",string.sub(ttf,ktag + 8, ktag + 11))
                --print(ktoffset .. " " .. shortlen)
                --make sure this is the type we are looking for
                if string.sub(ttf,ktoffset + 1, ktoffset + 4) == "\000\001\000\000" then
                    --print("made it this far")
                    ntables = s.unpack(">I4",(string.sub(ttf,ktoffset + 5, ktoffset + 8)))
                    ntables_bad = s.unpack(">I4","\016\000\000\000") 
                    if ntables >= ntables_bad then
                        --print("we have a match " .. ntables)
                        return 1
                    end 
                end
            end
        end
        offset = offset + shortlen  
    end
    return 0
end
